# -*- coding: utf-8 -*-
import sys
import subprocess
import os
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QTextEdit, QFileDialog, QMessageBox, QAction, QMenuBar
from PyQt5.QtCore import Qt, QDateTime  
class CustomizationTool(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        #self.create_menu()
        menu_bar = self.menuBar = QMenuBar(self)
        help_menu = menu_bar.addMenu("操作")

        install_action = QAction("安装Live Build", self)
        install_action.triggered.connect(self.install)
        help_menu.addAction(install_action)

        open_action = QAction("说明")
        open_action.triggered.connect(self.help)
        help_menu.addAction(open_action)

        about_action = QAction("关于", self)
        about_action.triggered.connect(self.about)
        help_menu.addAction(about_action)
        

    def initUI(self):
        self.setWindowTitle("Debian发行版定制工具")
        self.setGeometry(100, 100, 400, 400)

        # 选择工作目录
        self.working_dir_label = QLabel("工作目录:")
        self.working_dir_text = QLineEdit()
        self.working_dir_button = QPushButton("选择目录")
        self.working_dir_button.clicked.connect(self.selectWorkingDir)

        # 参数文本框
        self.cpu_text = QLineEdit("CPU架构，示例：amd64")
        self.distribution_text = QLineEdit("Debian版本代号，示例：bookworm")
        self.iso_application_text = QLineEdit("iso名称，示例：TestOS")
        self.iso_publisher_text = QLineEdit("publisher，示例：Test Project")
        self.iso_volume_text = QLineEdit("--iso-volume，示例：TestOS Live")

        # 生成构建脚本按钮
        self.generate_script_button = QPushButton("生成构建脚本")
        self.generate_script_button.clicked.connect(self.generateScript)

        # 生成配置文件按钮
        self.generate_config_button = QPushButton("生成配置文件")
        self.generate_config_button.clicked.connect(self.generateConfigFile)

        # 软件包区域
        self.package_label = QLabel("软件包（每个一行）:")
        self.package_text = QTextEdit()
        self.add_package_button = QPushButton("加入软件包")
        self.add_package_button.clicked.connect(self.addPackage)

        # 打开软件包目录按钮
        self.open_package_directory_button = QPushButton("打开deb目录")
        self.open_package_directory_button.clicked.connect(self.openPackageDirectory)

        # 系统配置区域
        self.system_config_label = QLabel("系统配置:")
        self.system_name_text = QLineEdit('NAME')
        self.system_website_text = QLineEdit('HOME_URL')
        self.system_support_link_text = QLineEdit('SUPPORT_URL')
        self.write_system_config_button = QPushButton("写入系统配置")
        self.write_system_config_button.clicked.connect(self.writeSystemConfig)

        # 用户信息区域
        self.user_info_label = QLabel("Live CD配置:")
        self.hostname_text = QLineEdit('HOSTNAME')
        self.username_text = QLineEdit('LIVE_USERNAME')
        self.fullname_text = QLineEdit('LIVE_USER_FULLNAME')
        self.set_user_info_button = QPushButton("设置")
        self.set_user_info_button.clicked.connect(self.setUserInfo)

        # 定制按钮
        self.customize_button = QPushButton("构建")
        self.customize_button.clicked.connect(self.customize)

        # 布局 
        working_layout = QHBoxLayout()  
        working_layout.addWidget(self.working_dir_label)
        working_layout.addWidget(self.working_dir_text)  
        working_layout.addWidget(self.working_dir_button)  
        build_layout =QHBoxLayout()
        build_layout.addWidget(self.generate_script_button)
        build_layout.addWidget(self.generate_config_button)
        pkg_layout =QVBoxLayout()
        pkg_layout.addWidget(self.add_package_button)
        pkg_layout.addWidget(self.open_package_directory_button)
        lb_layout = QHBoxLayout()
        lb_layout.addWidget(self.set_user_info_button)
        lb_layout.addWidget(self.customize_button)
        layout = QVBoxLayout()  
        # 添加到垂直布局中，作为水平布局的标签  
        layout.addSpacing(3)  # 添加间距，使下一项与前一项有一定的距离  
        layout.addLayout(working_layout)  # 添加水平布局（包含working_dir_text和working_dir_button）
        layout.addWidget(self.cpu_text)
        layout.addWidget(self.distribution_text)
        layout.addWidget(self.iso_application_text)
        layout.addWidget(self.iso_publisher_text)
        layout.addWidget(self.iso_volume_text)
        layout.addSpacing(3)  # 添加间距，使下一项与前一项有一定的距离  
        layout.addLayout(build_layout) 
        layout.addWidget(self.package_label)
        layout.addWidget(self.package_text)
        layout.addSpacing(3)  # 添加间距，使下一项与前一项有一定的距离  
        layout.addLayout(pkg_layout) 
        layout.addWidget(self.system_config_label)
        layout.addWidget(self.system_name_text)
        layout.addWidget(self.system_website_text)
        #layout.addWidget(self.system_support_link_text)
        layout.addWidget(self.write_system_config_button)
        layout.addWidget(self.user_info_label)
        layout.addWidget(self.hostname_text)
        layout.addWidget(self.username_text)
        layout.addWidget(self.fullname_text)
        #layout.addWidget(self.set_user_info_button)
        #layout.addWidget(self.customize_button)
        layout.addSpacing(3)  # 添加间距，使下一项与前一项有一定的距离  
        layout.addLayout(lb_layout) 

 
        self.setLayout(layout)


    def create_menu(self):
        menu_bar = self.menuBar()
        help_menu = menu_bar.addMenu("操作")

        install_action = QAction("安装Live Build", self)
        install_action.triggered.connect(self.install)
        help_menu.addAction(install_action)

        open_action = QAction("说明")
        open_action.triggered.connect(self.help)

        about_action = QAction("关于", self)
        about_action.triggered.connect(self.about)
        help_menu.addAction(about_action)
        help_action = QAction("说明", self)
        help_action.triggered.connect(self.help)
        help_menu.addAction(help_action)
        

    def selectWorkingDir(self):
        dir_path = QFileDialog.getExistingDirectory(self, "选择工作目录")
        self.working_dir_text.setText(dir_path)

    def generateScript(self):
        script_content = f'#!/bin/sh \n'
        script_content += f'lb config noauto --color --architecture {self.cpu_text.text()} --archive-area main contrib non-free non-free-firmware --bootappend-live boot=live components --debian-installer live --debian-installer-distribution {self.distribution_text.text()} --debian-installer-gui true --distribution {self.distribution_text.text()} --iso-application {self.iso_application_text.text()} --iso-publisher {self.iso_publisher_text.text()} --iso-volume {self.iso_volume_text.text()} --linux-packages linux-image linux-headers --mirror-binary https://mirrors.163.com/debian --mirror-binary-security https://mirrors.163.com/debian-security --mirror-bootstrap https://mirrors.163.com/debian --mirror-chroot https://mirrors.163.com/debian --mirror-chroot-security https://mirrors.163.com/debian-security --mirror-debian-installer https://mirrors.163.com/debian --uefi-secure-boot enable --security true --updates true \n'
        script_content += f'read -p "Press [Enter] to exit..."'
        #script_content = f'#!/bin/sh \n\n'
        #script_content += f'set -e\n'
        #script_content += f'lb config noauto \ \n'
        #script_content += f'    --color \ \n'
        #script_content += f'    --architecture amd64 \ \n'
        #script_content += f'    --archive-area "main contrib non-free non-free-firmware" \ \n'
        #script_content += f'    --bootappend-live "boot=live components" \ \n'
        #script_content += f'    --debian-installer live \ \n'
        #script_content += f"    --debian-installer-distribution {self.distribution_text.text()} \ \n"
        #script_content += f"    --debian-installer-gui true \ \n"
        #script_content += f"    --distribution {self.distribution_text.text()} \ \n"
        #script_content += f'    --iso-application "{self.iso_application_text.text()}" \ \n'
        #script_content += f'    --iso-publisher "{self.iso_publisher_text.text()}" \ \n'
        #script_content += f'    --iso-volume "{self.iso_volume_text.text()}" \ \n'
        #script_content += f'    --linux-packages "linux-image linux-headers" \ \n'
        #script_content += f'    --mirror-binary https://mirrors.163.com/debian \ \n'
        #script_content += f'    --mirror-binary-security https://mirrors.163.com/debian-security \ \n'
        #script_content += f'    --mirror-bootstrap https://mirrors.163.com/debian \ \n'
        #script_content += f'    --mirror-chroot https://mirrors.163.com/debian \ \n'
        #script_content += f'    --mirror-chroot-security https://mirrors.163.com/debian-security \ \n'
        #script_content += f'    --mirror-debian-installer https://mirrors.163.com/debian \ \n'
        #script_content += f'    --uefi-secure-boot enable \ \n'
        #script_content += f'    --security true \ \n'
        #script_content += f'    --updates true \ \n'
        #script_content += '''"${@}" \n'''
        #script_content += f"echo {self.distribution_text.text()} >> {self.working_dir_text.text()}/auto.sh\n"
        #script_content += f"echo {self.iso_application_text.text()} >> {self.working_dir_text.text()}/auto.sh\n"
        #script_content += f"echo {self.iso_publisher_text.text()} >> {self.working_dir_text.text()}/auto.sh\n"
        #script_content += f"echo {self.iso_volume_text.text()} >> {self.working_dir_text.text()}/auto.sh\n"
        with open(f"{self.working_dir_text.text()}/auto.sh", "w") as f:
            f.write(script_content)
        os.system(f"deepin-terminal -e vim {self.working_dir_text.text()}/auto.sh")    
        QMessageBox.information(self, "生成构建脚本", "构建脚本已生成！")

    def generateConfigFile(self):
        os.chdir(self.working_dir_text.text())
        print(f"当前工作目录已切换到: {os.getcwd()}")
        os.system(f'chmod +x auto.sh')
        #run_connect = f'cd {self.working_dir_text.text()} \n'
        #run_connect += f'sh auto.sh'
        #with open(f"{self.working_dir_text.text()}/run.sh", "w") as f:
        #    f.write(run_connect)
        #os.system(f'chmod +x run.sh')
        os.system("pwd")
        os.system(f"sh auto.sh")
        os.system('notify-send "配置文件已生成！"')
        QMessageBox.information(self, "生成配置文件", "配置文件已生成！")

    def addPackage(self):
        #os.system(f"touch {self.working_dir_text.text()}/config/package-lists/app.list.chroot")
        package_content = self.package_text.toPlainText()
        with open(f"{self.working_dir_text.text()}/config/package-lists/app.list.chroot", "a") as f:
            f.write(package_content)
        QMessageBox.information(self, "加入软件包", "软件包已加入！")

    def openPackageDirectory(self):
        package_directory = f"{self.working_dir_text.text()}/config/packages"
        subprocess.Popen(["xdg-open", package_directory])

    def writeSystemConfig(self):
        path = os.path.join(self.working_dir_text.text(), "config", "includes.chroot_after_packages", "etc")
        os.makedirs(path, exist_ok=True)
        system_config_content = f'PRETTY_NAME="{self.system_name_text.text()} "\n'
        system_config_content += f'NAME="{self.system_name_text.text()}" \n'
        system_config_content += f'VERSION_ID="{self.system_name_text.text()}" \n'
        system_config_content += f'VERSION="{self.system_name_text.text()}" \n'
        system_config_content += f'VERSION_CODENAME="{self.system_name_text.text()} \n'
        system_config_content += f'ID=debian\n'
        system_config_content += f'HOME_URL="{self.system_website_text.text()}" \n'
        with open(f"{self.working_dir_text.text()}/config/includes.chroot_after_packages/etc/os-release", "w") as f:
            f.write(system_config_content)
        QMessageBox.information(self, "写入系统配置", "系统配置已写入！")

    def setUserInfo(self):
        path = os.path.join(self.working_dir_text.text(), "config", "includes.chroot_after_packages", "etc", "live", "config.conf.d")
        os.makedirs(path, exist_ok=True)
        user_info_content = f'LIVE_HOSTNAME="{self.hostname_text.text()}"\n'
        user_info_content += '''LIVE_LOCALES="zh_CN.UTF-8"
LIVE_TIMEZONE="Asia/Shanghai" \n'''
        user_info_content += f'LIVE_USERNAME="{self.username_text.text()}"\n'
        user_info_content +=f'LIVE_USER_FULLNAME="{self.fullname_text.text()}"'
        #user_info_content = f'hostname="{self.hostname_text.text()}"\n'
        #user_info_content += f'USERNAME="{self.username_text.text()}"\n'
        #user_info_content += f'FULLNAME="{self.fullname_text.text()}"'
        with open(f"{self.working_dir_text.text()}/config/includes.chroot_after_packages/etc/live/config.conf.d/{self.system_name_text.text()}.conf", "w") as f:
            f.write(user_info_content)
        QMessageBox.information(self, "设置用户信息", "用户信息已设置！")

    def customize(self):
        build_script = f'cd {self.working_dir_text.text()}\n'
        build_script += f"sudo lb config\n"
        build_script += f"sudo lb build"
        with open(f"{self.working_dir_text.text()}/build.sh", "w") as f:
            f.write(build_script)
        os.chdir(self.working_dir_text.text())
        print(f"当前工作目录已切换到: {os.getcwd()}")
        os.system(f"deepin-terminal -e bash build.sh")

    def install(self):
        os.system('notify-send "开始安装LiveBuild..."')
        os.system("deepin-terminal -e bash /opt/com.zhsoft.lbtool/deb/install.sh")
        os.system('notify-send "LiveBuild安装完成！"')

    def help(self):
        QMessageBox.information(self, "帮助", "此为Debian发行版GUI定制工具，命令行基于Live Build项目\nlivebuild示例命令行\nlive-build的高级构建命令有三个，分别是：lb config\nlb build\nlb clean\n高级：\nlbbuild:\n构建过程按顺序分为bootstrap、chroot、binary、installer、source阶段，各种定制操作会应用在这些阶段中，对应二级构建命令lb bootstrap、lb chroot、lb installer、lb binary、lb source。用户通常只需要执行高级命令lb build，不需要直接执行二级构建命令")

    def about(self):
        current_year = QDateTime.currentDateTime().toString("yyyy")
        QMessageBox.information(self, "帮助", f"此为Debian发行版GUI定制工具，命令行基于Live Build项目\nCopyRight 2023-{current_year} ZhongHongSoftware") 

if __name__ == '__main__':
    app = QApplication(sys.argv)
    tool = CustomizationTool()
    tool.show()
    sys.exit(app.exec_())
